﻿using System;
using System.Globalization;
using System.Xml;
using SuppKids.Licensing.Common;

namespace SuppKids.Core.Security
{
    internal static class XmlDocumentExtensions
	{
		internal static LicenseDTO ToLicenseDTO(this XmlDocument xmlLicense)
		{
            return new LicenseDTO
			{
                LicenseId = SelectGuid(xmlLicense, LicenseDTO.LicenseIdField),
				CMID = SelectString(xmlLicense, LicenseDTO.CMIDField),
				ClientName = SelectString(xmlLicense, LicenseDTO.ClientNameField),
                PaymentDate = SelectDate(xmlLicense, LicenseDTO.PaymentDateField),
                ExpirationDate = SelectDate(xmlLicense, LicenseDTO.ExpirationDateField),
                MenuType = SelectEnum<MenuType>(xmlLicense, LicenseDTO.MenuTypeField),
			};
		}

        private static T SelectEnum<T>(XmlDocument xmlLicense, string elementName) where T : struct
        {
            T result;
            
            Enum.TryParse(SelectString(xmlLicense, elementName), true, out result);

            return result;
        }

        private static Guid SelectGuid(this XmlDocument xmlLicense, string elementName)
        {
            Guid result;

            Guid.TryParse(SelectString(xmlLicense, elementName), out result);

            return result;
        }

        private static DateTime SelectDate(this XmlDocument xmlLicense, string elementName)
		{
			DateTime result;

			DateTime.TryParse(SelectString(xmlLicense, elementName), CultureInfo.InvariantCulture, DateTimeStyles.None, out result);

			return result;
		}

        private static string SelectString(this XmlDocument xmlLicense, string elementName)
		{
			string resultValue = null;

			XmlNodeList nodeList = xmlLicense.SelectNodes(string.Format(CultureInfo.InvariantCulture, "license/{0}", elementName));
			if (nodeList != null && nodeList.Count > 0 && nodeList[0].FirstChild != null)
			{
				resultValue = nodeList[0].FirstChild.Value;
			}

			return resultValue;
		}
	}
}